-- UIRankNick
-- Created by chengb Jul/31/2015
-- 排行榜昵称、国籍输入

require "game/ui/form/ranklist/UINationSelect"

UIRankNick = class("UIRankNick", function()
    return cc.Layer:create();
end);

function UIRankNick.create(areaId)
    return UIRankNick.new(areaId);
end

-- 昵称最小长度
local MIN_LEN = 3;
local MAX_LEN = 16;

-- 构造函数
function UIRankNick:ctor(areaId)
    -- 初始化
    self:setName("UIRankNick");
    local node = cc.CSLoader:createNode("layout/ranklist/RankNick.csb");
    self:addChild(node);
    self.node = node;
    self.dungeonId = areaId;

    local uiComment = UIMgr.getCurrentScene():getFormByName("UIComment");
    if uiComment then
        -- 评论界面打开的
        self:setLocalZOrder(UIMgr.BONUS_NOTIFY_ZORDER + 1);
    elseif DungeonM.isInDungeon() then
        -- 迷宫内提高层级
        self:setLocalZOrder(UIMgr.TOP_MENU_ZORDER + 1);
    end

    -- 注册事件处理回调函数
    self:registerEventCallback();

    -- 注册点击事件
    self:registerTouchEvent();

    -- 重绘
    self:redraw();

    -- 适配
    self:resize();
end

-- 适配
function UIRankNick:resize()
    local node = self.node;

    -- bg居中显示并充满整个屏幕
    AlignM.fitToScreen(node, "bg");

    -- CT居中并缩放至合适大小
    AlignM.alignToCenter(node, "CT");

    -- BT置于底部并缩放至合适大小
    AlignM.alignToBottomCenter(node, "BT");
end

-- 注册点击事件
function UIRankNick:registerTouchEvent()
    -- 注册确定按钮点击事件
    local btnOk = findChildByName(self.node, "CT/btn_ok");
    local function onOkClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_click");
            self:trySave();
        end
    end
    btnOk:addTouchEventListener(onOkClick);
    TextStyleM.setTextStyle(btnOk, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnOk:setTitleText(getLocStr("btn_text_ok"));

    -- 注册'选择国家'链接点击事件
    -- 为了方便响应点击，需要增加一个panel，用来响应点击事件
    -- ps: 国旗也要响应点击事件
    local linkLabel = findChildByName(self.node, "CT/nationality_node/link");
    local linkPanel = findChildByName(self.node, "CT/nationality_node/link_panel");
    local nationIcon = findChildByName(self.node, "CT/nationality_node/icon");
    linkLabel:setTouchEnabled(true);
    local function onLinkClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_click");
            -- 打开国家选择界面
            closeFormByName("UINationSelect");
            local uiForm = UINationSelect.create(self.dungeonId);
            UIMgr.getCurrentScene():addForm(uiForm);
        end
    end
    linkLabel:addTouchEventListener(onLinkClick);
    linkPanel:addTouchEventListener(onLinkClick);
    nationIcon:addTouchEventListener(onLinkClick);

    -- 注册返回按钮点击事件
    local btnBack = findChildByName(self.node, "BT/btn_back");
    local function onBackClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            -- 关闭当前界面
            AudioM.playFx("button_return");
            closeFormByName("UIRankNick");
        end
    end
    AddBackEventHandler(self, btnBack, onBackClick);
    TextStyleM.setTextStyle(btnBack, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnBack:setTitleText(getLocStr("btn_text_back"));
end

-- 注册事件处理回调函数
function UIRankNick:registerEventCallback()
    -- 注册国籍选择事件
    EventMgr.register("UIRankNick", event.SELECT_NATION, function(args)
        local id = args.id;
        self:redrawNation(id);
    end);

    self:registerScriptHandler(function(ev)
        if ev == "exit" then
            cclog("UIRankNick 界面析构清理。");

            EventMgr.removeAll("UIRankNick");
        end
    end);
end

-- 重绘国籍信息
function UIRankNick:redrawNation(nationId)
    if nationId == nil then
        return;
    end

    self.nationId = nationId;

    local icon = TopM.queryNationality(nationId, "icon");
    local name = TopM.queryNationality(nationId, "name");

    -- 国家图标
    local CT = findChildByName(self.node, "CT");
    local nationImg = findChildByName(CT, "nationality_node/icon");
    nationImg:loadTexture(getNationalityIconPath(icon));

    -- 国家名称
    local nameLabel = findChildByName(CT, "nationality_node/name");
    TextStyleM.setTextStyle(nameLabel, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_WHITE, true, -2);
    nameLabel:setString(name);

    if TopM.isInlandType() then
        local linkLabel = findChildByName(CT, "nationality_node/link");
        local line = findChildByName(CT, "nationality_node/line");
        local width = nameLabel:getContentSize().width;
        local x = nameLabel:getPositionX() + width + 15;
        local linkX = linkLabel:getPositionX();
        local off = x - linkX;
        line:setPositionX(line:getPositionX() + off);
        linkLabel:setPositionX(x);
    end
end

-- 重绘
function UIRankNick:redraw()
    local CT = findChildByName(self.node, "CT");

    -- 国家
    local nationNoteLabel = findChildByName(CT, "nationality_node/nation_note");
    TextStyleM.setTextStyle(nationNoteLabel, textFontSize, TextStyleM.TEXT_COLOR_WHITE, true, -2);
    nationNoteLabel:setString(getLocStr("input_nation"));
    local textFontSize = TextStyleM.TEXT_SIZE_MIDDLE;
    if not isFullWidthLang() then
        textFontSize = TextStyleM.TEXT_SIZE_SMALL;
    end

    -- 获取当前的国籍id
    local nationId = ME.user.dbase:query("nation_id") or TopM.getDefaultNationId();
    local icon;
    local name;
    if nationId == nil or nationId == 0 then
        -- 默认设置
        icon = TopM.queryNationality(0, "icon");
        name = TopM.queryNationality(0, "name");
    else
        icon = TopM.queryNationality(nationId, "icon");
        name = TopM.queryNationality(nationId, "name");
    end

    -- 国家图标
    local nationImg = findChildByName(CT, "nationality_node/icon");
    nationImg:loadTexture(getNationalityIconPath(icon));

    -- 国家名称
    local nameLabel = findChildByName(CT, "nationality_node/name");
    TextStyleM.setTextStyle(nameLabel, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_WHITE, true, -2);
    nameLabel:setString(name);

    -- 选择国家
    local linkLabel = findChildByName(CT, "nationality_node/link");
    TextStyleM.setTextStyle(linkLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_BRIGHT_GREEN, true, -2);
    linkLabel:setString(getLocStr("select_nation"));

    if TopM.isInlandType() then
        local line = findChildByName(CT, "nationality_node/line");
        local width = nameLabel:getContentSize().width;
        local x = nameLabel:getPositionX() + width + 15;
        local linkX = linkLabel:getPositionX();
        local off = x - linkX;
        line:setPositionX(line:getPositionX() + off);
        linkLabel:setPositionX(x);
    end

    -- 昵称
    local nickNoteLabel = findChildByName(CT, "nick_node/nick_note");
    TextStyleM.setTextStyle(nickNoteLabel, textFontSize, TextStyleM.TEXT_COLOR_WHITE, true, -2);
    nickNoteLabel:setString(getLocStr("input_nickname"));

    -- 不同语言版本需要有偏移
    local offset = 0;

    if not isFullWidthLang() then
        -- TODO
        offset = 0;
    end

    -- 昵称输入
    local nickInput   = findChildByName(CT, "nick_node/input_nick");
    local nickInputBg = findChildByName(CT, "nick_node/bg_input");
    nickInput:setPositionX(nickInput:getPositionX() + offset);
    nickInputBg:setPositionX(nickInputBg:getPositionX() + offset);
    local editBoxSize = nickInput:getContentSize();

    local editBox = ccui.EditBox:create(editBoxSize, "images/ui/login/1.png");
    editBox:setAnchorPoint(cc.p(0, 0.5));
    editBox:setPosition(nickInput:getPosition());
    editBox:setFontName(getLocFontName());
    editBox:setFontSize(TextStyleM.TEXT_SIZE_SMALL2);
    editBox:setPlaceHolder(getLocStr("input_nickname"));
    editBox:setPlaceholderFontColor(TextStyleM.TEXT_COLOR_GRAY2);
    editBox:setFontColor(TextStyleM.TEXT_OUTLINE_COLOR_DARK);
    editBox:setMaxLength(16);
    editBox:setInputMode(cc.EDITBOX_INPUT_MODE_SINGLELINE);
    editBox:setReturnType(cc.KEYBOARD_RETURNTYPE_DONE);
    self.editBox = editBox;
    nickInput:getParent():addChild(editBox);
    nickInput:setVisible(false);

    -- 提示信息
    local tipLabel = findChildByName(CT, "rank_tip");
    TextStyleM.setTextStyle(tipLabel, TextStyleM.TEXT_SIZE_SMALL2, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true, -4);
    tipLabel:setString(getLocStr("rank_tip"));
end

-- 尝试保存
function UIRankNick:trySave()
    local nickname = self.editBox:getText();
    nickname = string.trim(nickname);

    if nickname == "" then
        -- 没输入昵称
        alert(getLocStr("please_input_nickname"));
        return;
    end

    -- 检查长度是否合法
    local len = string.len(nickname);

    cclog("nickname=%s, len = %d", nickname, len);

    if len < MIN_LEN then
        -- 昵称太短
        alert(string.format(getLocStr("nickname_too_short"), MIN_LEN));
        return;
    end

    if len > MAX_LEN then
        -- 昵称太长
        alert(getLocStr("nickname_too_long"));
        return;
    end

    -- 检查是否包含违禁字符
    local function isValid()
        -- 仅包含字母、数字、下划线和空格
        local pattern = "[%w_%s]";
        local length = string.len(nickname);
        for i = 1, length do
            local ch = string.sub(nickname, i, i);
            if nil == string.match(ch, pattern) then
                return false;
            end
        end
        return true;
    end

--    if not isValid() then
--        -- 包含违禁字符
--        confirm2(CONFIRM_TYPE_OK, getLocStr("hint"), getLocStr("nickname_contain_invalid_char"));
--        return;
--    end

    -- local nationId = self.nationId or TopM.getDefaultNationId();
    if self.nationId == nil then
        -- 打开国家选择界面
        closeFormByName("UINationSelect");
        local uiForm = UINationSelect.create(self.dungeonId);
        UIMgr.getCurrentScene():addForm(uiForm);
        return;
    end

    local function requestSave()
        Operation.cmd_set_rank_brief(nickname, self.nationId);
    end

    local nationName = TopM.queryNationality(self.nationId, "name");
    local icon = TopM.queryNationality(self.nationId, "icon");
    local nationIconPath = getNationalityIconPath(icon);

    local nicknameIconPath = getNationalityIconPath("nickname");

    local tip = getLocStr("ranklist_info_tip");
    local msg1 = getLocStr("ranklist_info_tip");
    local msg ={msg1, getLocStr("ranklist_nickname"), getLocStr("ranklist_nation"), nickname, nationName};
    local iconPath = {nicknameIconPath, nationIconPath};
    confirm3(CONFIRM_TYPE_OK_CANCEL, getLocStr("rank_info_set"), msg, iconPath, requestSave);
end